package db

import (
	"fmt"
	"time"

	_ "github.com/lib/pq"
	"github.com/xormplus/xorm"
)

// PostgresConnectTest ...
func PostgresConnectTest(Host, Port, Dbname, User, Password string) error {
	psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", Host, Port, User, Password, Dbname)
	//格式
	db, err := xorm.NewEngine("postgres", psqlInfo)
	if err != nil {
		return err
	}
	defer db.Close()
	err = db.Ping()
	return err
}

// PostgresSQLDump ...
func PostgresSQLDump(host, port, dbname, user, password, backupfilePath, zippwd string) (string, error) {
	psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
	//格式
	db, err := xorm.NewEngine("postgres", psqlInfo)
	if err != nil {
		return "", err
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		return "", err
	}
	nowtime := time.Now().Format("2006-01-02_15-04-05")
	dist := host + "_postgres_" + dbname + "_" + "_" + nowtime + ".sql"
	distzp := host + "_postgres_" + dbname + "_" + "_" + nowtime + ".zip"
	err = db.DumpAllToFile(backupfilePath + "/" + dist)
	if err != nil {
		return "", err
	}
	return SQLDumpZip(backupfilePath+"/"+dist, backupfilePath+"/"+distzp, zippwd)
}
